package util;

import gp.GP;
import gp.Generation;
import gp.Individuo;
import gp.Symbol;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Reader {
	String file_name;
	
	public Reader(String file_name){
		this.file_name = file_name;
	}
	
	public void read(GP gp) throws IOException{
		FileInputStream fstream = new FileInputStream(this.file_name);
		DataInputStream in  = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String strLine;
		String delims = "[\\s]+";
		String definitionDelims = "[\\s\\(\\)\\,]+";
		boolean reading_definition, reading_generation, reading_breed;
		reading_breed = reading_definition = reading_generation = false;
		Generation generation = null;
		while((strLine = br.readLine()) != null){
			strLine = strLine.trim();
			if(strLine.equals("definition:")){
				reading_definition = true;
				String definition = br.readLine();
				String[] tokens = definition.split(definitionDelims);
				for(int i = 2; i < tokens.length; i+=2){
					System.out.println(tokens[i]);
					String symbol = tokens[i];
					int degree = Integer.parseInt(tokens[i+1]);
					//register symbol in the alphabet
					gp.insert_symbol(symbol, degree);
				}
				reading_definition = false;
				continue;
			}
			
			if(strLine.equals("generation:")){
				reading_definition = reading_breed = false;
				reading_generation = true;
				if(generation != null){
					gp.insert_generation(generation);
				}
				generation = new Generation();
				continue;
			}
			String[] tokens = strLine.split(delims);
			if(tokens[0].equals("ind:")){
				float fitness = Float.parseFloat(tokens[1]);
				Stack<Symbol> symbolsStack = new Stack<Symbol>();
				for(int i = (tokens.length-1); i > 1; i--){
					symbolsStack.push(gp.get_symbol(tokens[i]));
				}
				Individuo ind = new Individuo(fitness, symbolsStack);
				generation.insert_individuo(ind);
				continue;
			}
			
			if(tokens[0].equals("breed:")){
				//read breeds
				continue;
			}
		}
		if(generation != null){
			gp.insert_generation(generation);
		}
		in.close();
	}

}
